﻿using System.Linq;
using Microsoft.EntityFrameworkCore;
using Qs.App.Base;
using Qs.App.Interface;
using Qs.Repository.Core;
using Qs.Repository.Interface;

namespace Qs.App
{
    /// <summary>
    /// 树状结构处理
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="TDbContext"></typeparam>
    public class AppBaseTree<T, TDbContext> : AppBaseString<T, TDbContext> where T : TreeEntity where TDbContext : DbContext
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="unitWork"></param>
        /// <param name="repository"></param>
        /// <param name="dbExtension"></param>
        /// <param name="auth"></param>
        public AppBaseTree(IUnitWork<TDbContext> unitWork, IRepository<T, TDbContext> repository, DbExtension dbExtension, IAuth auth) : base(unitWork, repository, dbExtension, auth)
        {
        }

        /// <summary>
        /// 更新树状结构实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        public void UpdateTreeObj<T>(T obj) where T : TreeEntity
        {
            CaculateCascade(obj);
            //获取旧的的CascadeId
            var cascadeId = Repository.FirstOrDefault(p => p.Id == obj.Id).CascadeId;
            //根据CascadeId查询子节点
            var listSon = Repository.Find(u => u.CascadeId.Contains(cascadeId) && u.Id != obj.Id)
                .OrderBy(u => u.CascadeId).ToList();

            //更新操作
            UnitWork.Update(obj);

            //更新子模块的CascadeId
            foreach (var son in listSon)
            {
                son.CascadeId = son.CascadeId.Replace(cascadeId, obj.CascadeId);
                if (son.ParentId == obj.Id)
                {
                    son.ParentName = obj.Name;
                }
                UnitWork.Update(son);
            }
            UnitWork.Save();
        }


    }
}